package util.webSearch;

import java.rmi.RemoteException;
import java.util.Iterator;
import java.util.LinkedList;

import org.apache.axiom.om.OMElement;
import org.apache.axis2.AxisFault;
import org.apache.axis2.databinding.types.UnsignedInt;
import org.apache.axis2.transport.http.HTTPConstants;

import util.parser.DeliciousURLInfoPost;
import util.parser.JsonParser;

import com.microsoft.schemas.livesearch._2008._03.search.LiveSearchServiceStub;
import com.microsoft.schemas.livesearch._2008._03.search.LiveSearchServiceStub.*;

public class BingQuery {
	static LiveSearchServiceStub stub = null;

	
	public static void main(String[] args) throws RemoteException {
		System.out.println(bingQuery("dinosaurs for kids", 40));

	}
	
	
	public static LinkedList<WebResult> bingQuery(String query, int max_results) {

		LinkedList<WebResult> res = new LinkedList<WebResult>();
		try {
			// Initialize the service
			stub = new LiveSearchServiceStub();
			stub._getServiceClient().getOptions().setProperty(
					HTTPConstants.CHUNKED, false);

			// Build the request
			LiveSearchServiceStub.SearchRequest searchRequest = BuildRequest(query, max_results);

			// Get the response
			SearchResponseE response = GetResponse(searchRequest);

			// Display the response
			getResponse(response,res);

		} catch (AxisFault e) {
			DisplayErrors(e);
		} catch (RemoteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
			
		return res;

	}

	private static void getResponse(SearchResponseE responseE,
			LinkedList<WebResult> res) {
		// TODO Auto-generated method stub

		SearchResponse response = responseE.getParameters();

		
		if(response.getWeb().getResults()==null)
			return;
		
		int startIndex = response.getWeb().getOffset().intValue() + 1;
		int endIndex = response.getWeb().getOffset().intValue()
				+ response.getWeb().getResults().getWebResult().length;

/*		// Display the results header.
		System.out.println("Live Search API Version " + response.getVersion());
		System.out.println("Web results for "
				+ response.getQuery().getSearchTerms());
		System.out.println("Displaying " + (startIndex) + " to " + (endIndex)
				+ " of " + response.getWeb().getTotal() + " results ");
		System.out.println();
*/
		// Display the Web results.
		StringBuilder builder = new StringBuilder();
		com.microsoft.schemas.livesearch._2008._03.search.LiveSearchServiceStub.WebResult[] results = response
				.getWeb().getResults().getWebResult();

		for (int i = 0; i < results.length; i++) {
			
			WebResult temp = new WebResult();
			
			temp.setSnippet(results[i].getDescription());
			temp.setUrl(results[i].getUrl());
			
			temp.setTitle(results[i].getTitle());
			temp.setRank(i+1);
			temp.setEngine(WebResult.BING);
			
			//delicious data
			DeliciousURLInfoPost del =  JsonParser.parseDeliciousInfoFromURL(results[i].getUrl().trim());
			temp.setDelicious(del);
		
			
			
			res.add(temp);
			/*builder.setLength(0);
			builder.append(results[i].getTitle());
			builder.append("\n");
			builder.append(results[i].getDescription());
			builder.append("\n");
			builder.append(results[i].getUrl());
			builder.append("\n");
			builder.append("Last Crawled: ");
			builder.append(results[i].getDateTime());
			builder.append("\n");
			System.out.println(builder.toString());*/
		}
	//	System.out.println();

	}


	private static SearchRequest BuildRequest(String query, int max_results) {
		// TODO Auto-generated method stub
		
		SearchRequest request = new SearchRequest();

		// Common request fields (required)
		request.setAppId("991F081D5E15ABB7C7948C5BE3E9B0C80061F0C4");
		request.setQuery(query);
		ArrayOfSourceType param = new ArrayOfSourceType();
		param.addSourceType(SourceType.Web);
		request.setSources(param);

		// Common request fields (optional)
		request.setVersion("2.0");
		request.setMarket("en-us");
		request.setAdult(AdultOption.Off);

		// Web-specific request fields (optional)
		WebRequest web = new WebRequest();
		request.setWeb(web);
		web.setCount(new UnsignedInt(max_results));
		web.setOffset(new UnsignedInt("0"));
	//	web.setFileType("DOC");
		ArrayOfWebSearchOption options = new ArrayOfWebSearchOption();
		options.addWebSearchOption(WebSearchOption.DisableHostCollapsing);
		options.addWebSearchOption(WebSearchOption.DisableQueryAlterations);
		web.setOptions(options);

		return request;
		
		
		
		
		
		
		
	}


	private static SearchRequest BuildRequest() {
		SearchRequest request = new SearchRequest();

		// Common request fields (required)
		request.setAppId("991F081D5E15ABB7C7948C5BE3E9B0C80061F0C4");
		request.setQuery("dinosaurs for kids");
		ArrayOfSourceType param = new ArrayOfSourceType();
		param.addSourceType(SourceType.Web);
		request.setSources(param);

		// Common request fields (optional)
		request.setVersion("2.0");
		request.setMarket("en-us");
		request.setAdult(AdultOption.Off);

		// Web-specific request fields (optional)
		WebRequest web = new WebRequest();
		request.setWeb(web);
		web.setCount(new UnsignedInt("50"));
		web.setOffset(new UnsignedInt("0"));
	//	web.setFileType("DOC");
		ArrayOfWebSearchOption options = new ArrayOfWebSearchOption();
		options.addWebSearchOption(WebSearchOption.DisableHostCollapsing);
		options.addWebSearchOption(WebSearchOption.DisableQueryAlterations);
		web.setOptions(options);

		return request;
	}

	private static SearchResponseE GetResponse(SearchRequest searchRequest)
			throws RemoteException {
		SearchRequestE searchRequestE = new SearchRequestE();
		searchRequestE.setParameters(searchRequest);
		return  stub.search(searchRequestE);
	}

	private static void DisplayResponse(SearchResponseE responseE) {
		SearchResponse response = responseE.getParameters();

		int startIndex = response.getWeb().getOffset().intValue() + 1;
		int endIndex = response.getWeb().getOffset().intValue()
				+ response.getWeb().getResults().getWebResult().length;

		// Display the results header.
		System.out.println("Live Search API Version " + response.getVersion());
		System.out.println("Web results for "
				+ response.getQuery().getSearchTerms());
		System.out.println("Displaying " + (startIndex) + " to " + (endIndex)
				+ " of " + response.getWeb().getTotal() + " results ");
		System.out.println();

		// Display the Web results.
		StringBuilder builder = new StringBuilder();
		com.microsoft.schemas.livesearch._2008._03.search.LiveSearchServiceStub.WebResult[] results = response
				.getWeb().getResults().getWebResult();

		for (int i = 0; i < results.length; i++) {
			builder.setLength(0);
			builder.append(results[i].getTitle());
			builder.append("\n");
			builder.append(results[i].getDescription());
			builder.append("\n");
			builder.append(results[i].getUrl());
			builder.append("\n");
			builder.append("Last Crawled: ");
			builder.append(results[i].getDateTime());
			builder.append("\n");
			System.out.println(builder.toString());
		}
		System.out.println();
	}

	@SuppressWarnings("unchecked")
	private static void DisplayErrors(AxisFault e) {
		System.out.println("Live Search API errors.\n");

		System.out.println("FaultString:" + e.getReason());
		System.out.println("FaultDetails:\n");

		OMElement element = e.getDetail();
		Iterator iterator = element.getChildElements();
		while (iterator.hasNext()) {

			OMElement childElement = (OMElement) iterator.next();
			Iterator childIterator = childElement.getChildElements();
			while (childIterator.hasNext()) {
				OMElement ele = (OMElement) childIterator.next();
				System.out.println("\t" + ele.getLocalName() + " : "
						+ ele.getText());
			}
		}
	}
}